<template>
    <mu-card class="monitor">
        <!--<mu-card-header>游戏修改器</mu-card-header>-->
        <mu-card-text>
            <p v-if="is_loading_room_list_info">加载中……</p>
            <template v-else>
                <p v-if="!room_page_info.list.length">无房间</p>
            </template>
            <mu-row gutter>
                <mu-col v-for="(room, i) in room_page_info.list"
                        :key="room.id"
                        width="100"
                        tablet="50"
                        desktop="20">
                    <mu-paper class="room-item"
                              :zDepth="room._zDepth"
                              @mouseenter.native="room._zDepth=2"
                              @mouseleave.native="room._zDepth=1">
                        <mu-list>
                            <mu-sub-header>房号：{{room.id}}</mu-sub-header>
                            <mu-list-item disableRipple
                                          :describeText="room.player_number+'人模式'"
                                          :title="room.mode">
                                <mu-icon-button slot="right"
                                                icon="edit"
                                                @click="showCheatPanel(room)"
                                                tooltip="改牌"></mu-icon-button>
                            </mu-list-item>
                        </mu-list>
                        <mu-divider />
                        <mu-list>
                            <mu-sub-header>玩家信息</mu-sub-header>
                            <mu-list-item v-for="(player,player_i) in room.players"
                                          :key="player.id"
                                          :describeText="'玩家'+(player_i+1)"
                                          :title="player.info.username">
                                <mu-avatar slot="left"
                                           :src="player.info.headimgurl" />
                            </mu-list-item>
                        </mu-list>
                    </mu-paper>
    
                </mu-col>
            </mu-row>
        </mu-card-text>
        <mu-card-actions>
            <mu-pagination :total="room_page_info.total"
                           :current="room_page_info.page"
                           :pageSize="room_page_info.num"
                           :showSizeChanger="true"
                           :pageSizeOption="[10,20,50]"
                           @pageChange="handleCurrentChange"
                           @pageSizeChange="handleSizeChange">
            </mu-pagination>
        </mu-card-actions>
    
        <mu-dialog dialogClass="custom-cards-dialog"
                   :open="is_show_cheat"
                   :title="'修改'+(selected_room&&selected_room.id)+'的牌组'"
                   scrollable>
            <div v-if="selected_room">
                <mu-flexbox :gutter="5">
                    <mu-flexbox-item v-for="(player,player_i) in selected_room.players"
                                     :key="player.id">
                        <mu-paper :zDepth="1">
                            <mu-list>
                                <mu-list-item disableRipple
                                              :describeText="'玩家'+(player_i+1)"
                                              :title="player.info.username">
                                    <mu-avatar slot="left"
                                               :src="player.info.headimgurl" />
                                </mu-list-item>
                                <mu-list-item disableRipple>
                                    <mu-select-field style="min-width:10em;"
                                                     v-model="custom_flow_lock[player_i]"
                                                     @change="setCustomLock(player_i,player.id)"
                                                     label="使用牌组">
                                        <mu-menu-item :value="false"
                                                      title="自动" />
                                        <mu-menu-item v-for="custom_index in selected_room.player_number"
                                                      :disabled="player_id_lock_map_list[player_i][custom_index-1]"
                                                      :value="custom_index-1"
                                                      :title="'定制牌组'+custom_index" />
                                    </mu-select-field>
                                </mu-list-item>
                            </mu-list>
                        </mu-paper>
                    </mu-flexbox-item>
                </mu-flexbox>
    
                <mu-flexbox :gutter="5">
                    <mu-flexbox-item v-for="custom_index in selected_room.player_number"
                                     :key="custom_index">
                        <mu-paper :zDepth="1">
                            <mu-list>
                                <mu-sub-header>定制牌组{{custom_index}}</mu-sub-header>
                                <mu-list-item @click="addSelectedCardToCustomCardList(custom_flow_cards[custom_index-1])">
                                    <div class="card-list">
                                        <mu-paper draggable
                                                  class="card-item select-able"
                                                  @click.native="removeCardFromCustomCardList(card_item,custom_flow_cards[custom_index-1])"
                                                  v-for="(card_item,i) of custom_flow_cards[custom_index-1]"
                                                  :key="card_item+'|'+i"
                                                  v-html="cartNameToHtml(card_item&&card_item._txt)">
                                        </mu-paper>
                                    </div>
                                </mu-list-item>
                            </mu-list>
                        </mu-paper>
                    </mu-flexbox-item>
                </mu-flexbox>
                <div class="card-list"
                     style="max-width:720px; margin: 0 auto;">
                    <template v-for="(card_item,i) of CARD_LIST">
                        <mu-paper draggable
                                  :zDepth="card_item.is_selected?2:1"
                                  class="card-item select-able"
                                  @click.native="card_item.is_selected=!card_item.is_selected"
                                  :class="{selected: !card_item.is_used&&card_item.is_selected, used: card_item.is_used}"
                                  :key="card_item+''"
                                  v-html="cartNameToHtml(card_item._txt)">
                        </mu-paper>
                    </template>
                </div>
                <div style="text-align:center;">
                    <mu-radio :checkedIcon="setted_rounds.indexOf(i-1)!==-1?'bug_report':''"
                              :uncheckIcon="setted_rounds.indexOf(i-1)!==-1?'bug_report':''"
                              v-for="i in selected_room.max_round"
                              :key="i"
                              :label="'第'+i+'局'"
                              name="target-round"
                              :disabled="(i-1)<(selected_room.max_round-selected_room.cur_round)"
                              :nativeValue="(i-1)+''"
                              v-model="target_round"
                              class="target-round" />
                </div>
            </div>
            <mu-flat-button slot="actions"
                            @click="is_show_cheat = false"
                            primary
                            label="取消" />
            <mu-flat-button slot="actions"
                            primary
                            :disabled="is_putting_data"
                            @click="submitCheatCards">
                <mu-circular-progress v-if="is_putting_data"
                                      style="margin:0;position: relative;top: 5px;height:50px"
                                      :size="25" />
                <span v-else/>确认</span>
            </mu-flat-button>
        </mu-dialog>
    </mu-card>
</template>
<script>
import { componentWrapper, on } from './componentWrapper';
import Card, { CardList, CARD_LIST } from "./Card";

export default componentWrapper({
    pagination: {
        request(current_route, callback) {
            callback(vm => vm.is_loading_room_list_info = true);
            socket_promise.then(() => {
                socket.emit("online-room-info", {
                    search: current_route.query.room,
                    num: current_route.query.num,
                    page: current_route.query.page,
                    auto_watch: true
                });
                socket.once("online-room-info-result", room_page_info => {
                    callback(vm => {
                        vm.is_loading_room_list_info = false;
                        room_page_info.list.forEach(room => {
                            room._zDepth = 1;
                        });
                        vm.room_page_info = room_page_info;
                    });
                });
            });
        }
    },
    data() {
        return {
            total_player_number: 0,
            room_page_info: {
                total: 0,
                page: 1,
                num: 10,
                list: [],
            },
            is_loading_room_list_info: false,
            is_show_cheat: false,
            is_putting_data: false,
            selected_room: null,
            custom_flow_cards: [],
            custom_flow_lock: [],
            custom_cards_index_player_id_map: {},
            player_id_lock_map_list: [],
            CARD_LIST,
            target_round: '0',
            setted_rounds: []
        }
    },
    created() {
        window.vm = this;
        socket_promise.then(() => {
            const offs = this.offs;
            // 监听在线人数变动
            offs[offs.length] = on(socket, "online-player-number", total_player_number => {
                this.total_player_number = total_player_number;
            });
            // 请求在线人数数量
            socket.emit("online-player-number");
            // 监听在线房间数量变动
            offs[offs.length] = on(socket, "online-room-number", total_room_number => {
                this.room_page_info.total = total_room_number;
                this.refreshPage();
            });
            // 监听房间状态变动
            offs[offs.length] = on(socket, "room-changed", changed_room => {
                this.room_page_info.list && this.room_page_info.list.some(room => {
                    if (room.id === changed_room.id) {
                        Object.assign(room, changed_room);
                    }
                });
                if (this.selected_room && this.selected_room.id === changed_room.id) {
                    this.initTargetRound();
                    this.initCustomLock();
                }
            });
            // 监听作弊房间的序号变动
            offs[offs.length] = on(socket, "--cheat-room-flows-result--", rounds => {
                this.setted_rounds = rounds;
            });
        });

    },
    methods: {
        initTargetRound() {
            const selected_room = this.selected_room;
            var target_round = this.target_round | 0;
            var min_round = selected_room.max_round - selected_room.cur_round
            if (target_round < min_round) {
                this.target_round = min_round + '';
            }
        },
        initCustomLock() {
            const { selected_room, custom_cards_index_player_id_map } = this;
            const players = selected_room.players;

            this.custom_flow_lock.fill(false);
            this.custom_flow_lock = players.map((player) => {
                return custom_cards_index_player_id_map[player.id]
            });
        },
        showCheatPanel(room_info) {
            this.selected_room = room_info;
            this.is_show_cheat = true;
            this.custom_flow_cards = [];
            this.custom_flow_lock = [];
            this.custom_cards_index_player_id_map = {};
            this.player_id_lock_map_list = [];
            this.setted_rounds = [];
            socket.emit("--cheat-room-flows--", {
                flow_id_prefix: "FLOW|" + (this.selected_room.next_hash_id||this.selected_room.hash_id).replace("ROOM|", "") + "|"
            });
            for (var i = 0; i < room_info.player_number; i += 1) {
                this.custom_flow_cards.push(Array.from({ length: 13 }).fill(""));
                this.custom_flow_lock.push(false);
                this.player_id_lock_map_list.push(Array.from({ length: room_info.player_number }).fill(false));
            }
            if (this.__player_id_lock_map_list_off) {
                this.__player_id_lock_map_list_off();
            }
            CARD_LIST.forEach(card => {
                card.is_used = false;
                card.is_selected = false;
            });
            this.__player_id_lock_map_list_off = (() => {
                const offs = ["custom_flow_lock", "custom_cards_index_player_id_map"].map(key => this.$watch(key, () => {
                    clearTimeout(this.__player_id_lock_map_list_ti);
                    this.__player_id_lock_map_list_ti = setTimeout(() => {
                        const { custom_flow_lock, custom_cards_index_player_id_map, player_id_lock_map_list, selected_room } = this;
                        console.group();
                        console.log(custom_flow_lock.join())
                        console.log(JSON.stringify(custom_cards_index_player_id_map));
                        this.player_id_lock_map_list = player_id_lock_map_list.map((player_id_lock_map, player_index) => {
                            const player = selected_room.players[player_index];
                            var new_map = player_id_lock_map.map((is_disabled, list_index) => {
                                var enable = false;
                                if (custom_flow_lock.indexOf(list_index) === -1) {
                                    enable = true;
                                } else {
                                    if (player && custom_cards_index_player_id_map[player.id] === list_index) {
                                        enable = true;
                                    }
                                }
                                return !enable;
                            });
                            return new_map;
                        });
                        console.log(player_id_lock_map_list.join('\n'))
                        console.groupEnd();
                    }, 200);
                }))
                return () => offs.forEach(off => off());
            })();
            this.initTargetRound();
        },
        setCustomLock(player_index, player_id) {
            vm.$nextTick(() => {
                let lock_info_index;
                this.custom_cards_index_player_id_map[player_id] = this.custom_flow_lock[player_index];
            });
        },
        addSelectedCardToCustomCardList(container) {
            const selected_card_list = CARD_LIST.filter(card => {
                return !card.is_used && card.is_selected
            });
            if (!selected_card_list.length) {
                return
            }
            for (var i = 0; i < container.length; i += 1) {

                if (!container[i]) {
                    var card = selected_card_list.shift();
                    card.is_used = true;
                    card.is_selected = false;
                    container.splice(i, 1, card);
                    console.log(i, container.length)
                }
                if (!selected_card_list.length) {
                    break;
                }
            }
            // 排序
            container.sort((card_a, card_b) => {
                var card_a_val = card_a ? +card_a : 1000;
                var card_b_val = card_b ? +card_b : 1000;
                return card_a_val - card_b_val
            });
        },
        removeCardFromCustomCardList(card_item, container) {
            if (card_item) {
                var index = container.indexOf(card_item);
                console.log(index, container);
                if (index !== -1) {
                    card_item.is_used = false;
                    container.splice(index, 1, "");
                    console.log(container.length);
                }
            }
        },
        submitCheatCards() {
            this.is_putting_data = true;
            const flow_id = "FLOW|" + (this.selected_room.next_hash_id||this.selected_room.hash_id).replace("ROOM|", "") + "|" + this.target_round;
            socket.emit("--cheat-flow-cards--", {
                room_id: this.selected_room.id,
                player_id_customs_cards_index_map: this.custom_cards_index_player_id_map,
                custom_cards_list: this.custom_flow_cards,
                flow_id,
            });
            socket.once("--cheat-flow-cards-result--", () => {
                this.is_putting_data = false;
                this.is_show_cheat = false;
            });
        },
        cartNameToHtml(card) {
            if (!card) {
                return `<div class='img' style="color:#666;">
                            <div class='symbol'>🎲</div>
                            <div class='number'>自动</div>
                        </div>`
            }
            const card_info = card.split("_");
            const [type, num] = card_info;
            const symbol_map = {
                "黑桃": "♠",
                "方块": "♦",
                "红心": "♥",
                "梅花": "♣",
            };
            const color_map = {
                "黑桃": "#000",
                "方块": "#e30",
                "红心": "#F00",
                "梅花": "#333",
            };
            return `<div class='img' style="color:${color_map[type]};">
                        <div class='symbol'>${symbol_map[type]}</div>
                        <div class='number'>${num}</div>
                    </div>`
        },
    }
});
</script>
<style>
.symbol {
    font-size: 1.8em;
}

.custom-cards-dialog {
    max-width: none;
}

.setted {}
</style>
<style scoped>
.room-item {
    margin-bottom: 1em;
}

.card-list {
    display: flex;
    flex-wrap: wrap;
    user-select: none;
    justify-content: center;
}

.card-item {
    flex: 44px 0;
    margin: 5px;
    text-align: center;
}

.select-able {
    cursor: pointer;
    background-color: #eee;
}

.select-able.selected {
    transform: scale(1.1);
    /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#b8e1fc+0,a9d2f3+10,90bae4+25,90bcea+37,90bff0+50,6ba8e5+51,a2daf5+83,bdf3fd+100;Blue+Gloss+%231 */
    background: rgb(184, 225, 252);
    /* Old browsers */
    background: -moz-linear-gradient(top, rgba(184, 225, 252, 1) 0%, rgba(169, 210, 243, 1) 10%, rgba(144, 186, 228, 1) 25%, rgba(144, 188, 234, 1) 37%, rgba(144, 191, 240, 1) 50%, rgba(107, 168, 229, 1) 51%, rgba(162, 218, 245, 1) 83%, rgba(189, 243, 253, 1) 100%);
    /* FF3.6-15 */
    background: -webkit-linear-gradient(top, rgba(184, 225, 252, 1) 0%, rgba(169, 210, 243, 1) 10%, rgba(144, 186, 228, 1) 25%, rgba(144, 188, 234, 1) 37%, rgba(144, 191, 240, 1) 50%, rgba(107, 168, 229, 1) 51%, rgba(162, 218, 245, 1) 83%, rgba(189, 243, 253, 1) 100%);
    /* Chrome10-25,Safari5.1-6 */
    background: linear-gradient(to bottom, rgba(184, 225, 252, 1) 0%, rgba(169, 210, 243, 1) 10%, rgba(144, 186, 228, 1) 25%, rgba(144, 188, 234, 1) 37%, rgba(144, 191, 240, 1) 50%, rgba(107, 168, 229, 1) 51%, rgba(162, 218, 245, 1) 83%, rgba(189, 243, 253, 1) 100%);
    /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b8e1fc', endColorstr='#bdf3fd', GradientType=0);
    /* IE6-9 */
}

.select-able.used {
    background-color: #999;
    box-shadow: none;
}

.target-round {
    padding-right: 1em;
    margin-right: 1em;
}
</style>